/*
 * @lc app=leetcode.cn id=530 lang=javascript
 *
 * [530] 二叉搜索树的最小绝对差
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */


function treeToArr (tree) {
    let arr = []

    function fun(tree) {
        if (tree.val !== undefined) {
            arr.push(tree.val)
        }
        if (tree.left) {
            fun(tree.left)
        }
        if (tree.right) {
            fun(tree.right)
        }
    }

    fun(tree)

    return arr
}

/**
 * @param {TreeNode} root
 * @return {number}
 */
var getMinimumDifference = function(root) {
    let arr = treeToArr(root)
    arr.sort((a, b) => a - b)
    let res = arr.reduce((total, currVal, currIndex) => {
        if (currIndex === 0) {
            return -1
        }
        let diff = currVal - arr[currIndex - 1]
        if (total === -1 || diff < total) {
            return diff
        }
        return total
    }, -1)
    return res
};
// @lc code=end

/* 

    二叉树转数组，数组计算绝对差值

*/
